/*
 * @Description: 
 * @Author: 葛玉根
 * @Date: 2021-03-06 20:26:31
 * @LastEditTime: 2021-03-07 20:34:27
 * @LastEditors: 葛玉根
 */
import { Effect, ImmerReducer, Reducer, Subscription } from 'umi';
import { classRoomDataApi, deleclassRoomDataApi, addclassRoomDataApi} from '@/api/classRoomAdministrationApi'
import { classRoomDataType} from '@/interface/classRoomAdministration'
export interface ClassRoomModelState {
    data: classRoomDataType[],
    deleClassRoomFlag:boolean
}

export interface ClassRoomModelType {
    namespace: 'classroom';
    state: ClassRoomModelState;
    effects: {
        getClassRoom: Effect;
        deleClassRoom: Effect;
        addClassRoom: Effect;
    };
    reducers: {
        save: Reducer<ClassRoomModelState>;
        // 启用 immer 之后
        // save: ImmerReducer<ClassRoomModelState>;
    };
    subscriptions: { setup: Subscription };
}

const ClassRoomModel: ClassRoomModelType = {
    namespace: 'classroom',

    state: {
        data: [],
        deleClassRoomFlag:false
    },

    effects: {
        *getClassRoom({ payload }, { call, put }) {
            let res = yield call(classRoomDataApi)
            if (res.code === 1) {
                yield put({
                    type: 'save',
                    payload: { data: res.data }
                })
            }
        },
        *deleClassRoom({ payload }, { call, put }) {
            let res = yield call(deleclassRoomDataApi, payload)
            if (res.code === 1) {
                yield put({
                    type: 'save',
                    payload: { deleClassRoomFlag: true }
                })
                yield put({
                    type: 'getClassRoom'
                })
            }
        },
        *addClassRoom({ payload }, { call, put }) {
            let res = yield call(addclassRoomDataApi,payload)
            if (res.code === 1) {
                yield put({
                    type: 'getClassRoom',
                })
            }
        },
    },
    reducers: {
        save(state, action) {
            return {
                ...state,
                ...action.payload,
            };
        },
        // 启用 immer 之后
        // save(state, action) {
        //   state.name = action.payload;
        // },
    },
    subscriptions: {
        setup({ dispatch, history }) {
            return history.listen(({ pathname }) => {
                // if (pathname === '/') {
                //     dispatch({
                //         type: 'getClassRoom',
                //     })
                // }
            });
        }
    }
};

export default ClassRoomModel;